#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import subprocess


def collect():
    filter_keys = ['Serial Number', 'Product Name', 'UUID', 'Wake-up Type']
    raw_data = {}

    for key in filter_keys:
        try:
            res = subprocess.Popen("sudo dmidecode -t system|grep '%s'" % key,
                                   stdout=subprocess.PIPE, shell=True)
            result = res.stdout.read().decode()
            data_list = result.split(':')

            if len(data_list) > 1:
                raw_data[key] = data_list[1].strip()
            else:
                raw_data[key] = ''
        except Exception as e:
            print(e)
            raw_data[key] = ''

    data = dict()
    data['asset_type'] = 'server'
    data['sn'] = raw_data['Serial Number']
    data['model'] = raw_data['Product Name']
    data['uuid'] = raw_data['UUID']
    data['wake_up_type'] = raw_data['Wake-up Type']

    data.update(get_os_info())
    data.update(get_cpu_info())
    data.update(get_ram_info())
    data.update(get_manage_ip())
    data.update(get_nic_info())
    return data


def get_manage_ip():
    ip = subprocess.Popen(
        "ip addr | egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | egrep '^192\.168|^172\.' | egrep -v '\.255$' | head -n 1",
        stdout=subprocess.PIPE, shell=True)
    manage_ip = ip.stdout.read().decode().strip()
    data_ip = {
        'manage_ip': "%s" % manage_ip
    }
    return data_ip


def get_os_info():
    """
    获取操作系统信息
    :return:
    """
    distributor = subprocess.Popen("lsb_release -a|grep 'Distributor ID'",
                                   stdout=subprocess.PIPE, shell=True)
    distributor = distributor.stdout.read().decode().split(":")

    release = subprocess.Popen("lsb_release -a|grep 'Description'",
                               stdout=subprocess.PIPE, shell=True)

    release = release.stdout.read().decode().split(":")
    data_dic = {
        "os_distribution": distributor[1].strip() if len(distributor) > 1 else "",
        "os_release": release[1].strip() if len(release) > 1 else "",
        "os_type": "Linux",
    }
    return data_dic


def get_cpu_info():
    """
    获取cpu信息
    :return:
    """
    raw_cmd = 'cat /proc/cpuinfo'

    raw_data = {
        'cpu_model': "%s |grep 'model name' |head -1 " % raw_cmd,
        'cpu_count':  "%s |grep  'processor'|wc -l " % raw_cmd,
        'cpu_core_count': "%s |grep 'cpu cores' |awk -F: '{SUM +=$2} END {print SUM}'" % raw_cmd,
    }

    for key, cmd in raw_data.items():
        try:
            result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
            raw_data[key] = result.stdout.read().decode().strip()
        except ValueError as e:
            print(e)
            raw_data[key] = ""

    data = {
        "cpu_count": raw_data["cpu_count"],
        "cpu_core_count": raw_data["cpu_core_count"]
        }

    cpu_model = raw_data["cpu_model"].split(":")

    if len(cpu_model) > 1:
        data["cpu_model"] = cpu_model[1].strip()
    else:
        data["cpu_model"] = ''

    return data


def get_ram_info():
    """
    获取内存信息
    Memory Device:
    :return:
    """
    total_mem = subprocess.Popen(
        "free -g|grep Mem|awk -F ' ' '{print $2}'",stdout=subprocess.PIPE, shell=True)
    total_capacity = total_mem.stdout.read().decode().strip()
    
    used_mem = subprocess.Popen(
        "free -g|grep Mem|awk -F ' ' '{print $3}'",stdout=subprocess.PIPE, shell=True)
    used_capacity = used_mem.stdout.read().decode().strip()

    ram_data = {
        'total_capacity': "%s" % total_capacity,
        'used_capacity': "%s" % used_capacity 
    }
    return ram_data



def get_nic_info():
    """
    获取网卡信息
    :return:
    """
    raw_data = subprocess.Popen("ifconfig -a", stdout=subprocess.PIPE, shell=True)
    raw_data = raw_data.stdout.read().decode().split("\n")

    nic_dic = dict()

    mac_addr = ''
    ip_address = ''
    net_mask = ''
    mac_addr = ''
     
    for line in raw_data:
        if "flags" in line:
            nic_name = line.split()[0]
         
        if "inet" in line:
          if " netmask" in line:
            nic_ip =  line.split()
            ip_address = nic_ip[1]
            net_mask = nic_ip[3] 
    
        if "ether" in line:
            mac_addr = line.split()[1]
            nic_dic[mac_addr] = {'name': nic_name,
                                 'mac': mac_addr,
                                 'ip_address': ip_address,
                                 'net_mask': net_mask,
                                 }
            nic_name = ''
            ip_address = ''
            net_mask = ''
            mac_addr = ''   
    nic_list = []
    for k, v in nic_dic.items():
        nic_list.append(v)

    return {'nic': nic_list}

if __name__ == "__main__":
    # 收集信息功能测试
    data = collect()
    print(data)
